"use client";
import { Checkbox, Form, Input } from "antd";
import style from "./index.module.scss";
import {
  EyeInvisibleOutlined,
  EyeTwoTone,
  UserOutlined,
  LockOutlined,
} from "@ant-design/icons";
import PrimaryButton from "../PrimaryButton";
import { useState } from "react";
import { login, userRegister } from "@/api";
import { useRouter } from "next/navigation";
import { message } from "antd";
import { useStore, useStoreType } from "@/zustand/store";

export type FieldType = {
  userAccount: string;
  userPassword: string;
  remember?: string;
};

interface BaseFormProps {
  register: boolean;
  setRegister: (value: boolean) => void;
}
export default function BaseForm(props: BaseFormProps) {
  const { register, setRegister } = props;
  const [checked, setChecked] = useState(false);
  const router = useRouter();
  const [form] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();
  const setLogin = useStore((state: useStoreType) => state.setLogin);
  const setUserId = useStore((state: useStoreType) => state.setUserId);
  const onSucess = async (values: FieldType) => {
    if (register) {
      const res = await userRegister({
        userAccount: values.userAccount,
        userPassword: values.userPassword,
      });
      res.data.code === 200
        ? messageApi.success(res.data.msg)
        : message.error(res.data.msg);
      setTimeout(() => {
        form.resetFields();
      }, 500);
    } else {
      const res = await login({
        userAccount: values.userAccount,
        userPassword: values.userPassword,
      });
      if (res.data.code === 200) {
        values.userAccount === "admin"
          ? router.push("/Manage")
          : router.push("/");
      } else {
        messageApi.error(res.data.msg);
      }
      setLogin(res.data.data);
      setUserId(Number(res.data.msg));
    }
  };
  const onFailed = (value: any) => {
    console.log(value);
  };

  return (
    <div>
      {contextHolder}
      <Form
        form={form}
        name="basic"
        wrapperCol={{ span: 16, offset: 4 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: false }}
        className={style["baseFormContainer"]}
        onFinish={onSucess}
        onFinishFailed={onFailed}
      >
        <Form.Item<FieldType>
          name="userAccount"
          rules={[{ required: true, message: "请输入用户名" }]}
        >
          <Input
            placeholder="请输入用户名"
            size="large"
            prefix={<UserOutlined />}
          />
        </Form.Item>

        <Form.Item<FieldType>
          name="userPassword"
          rules={[{ required: true, message: "请输入密码" }]}
        >
          <Input.Password
            placeholder="请输入密码"
            iconRender={(visible) =>
              visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />
            }
            size="large"
            prefix={<LockOutlined />}
          />
        </Form.Item>

        <Form.Item<FieldType>
          name="remember"
          valuePropName="checked"
          wrapperCol={{ offset: 4 }}
        >
          <Form.Item>
            {!register && (
              <Checkbox
                style={{ color: "rgba(0, 0, 0, 0.5)" }}
                onChange={(e) => setChecked(e.target.checked)}
              >
                记住密码
              </Checkbox>
            )}

            <span
              className={style["labelRegister"]}
              onClick={() => setRegister(!register)}
            >
              {register ? "已有账号？去登录>>" : "还没有账号？去注册>>"}
            </span>
          </Form.Item>
        </Form.Item>
        <Form.Item>
          <PrimaryButton
            className={style["primary"]}
            register={register}
            checked={checked}
            htmlType="submit"
          />
        </Form.Item>
      </Form>
    </div>
  );
}
